#ifndef ENHANCED_PAGING_CONTROLLER_H
#define ENHANCED_PAGING_CONTROLLER_H

#include "paging_controller.h"
#include "diff_util.h"
#include "async_paging_differ.h"
#include <memory>
#include <future>

// ArkUI_NodeHandle 在 arkui/native_type.h 中已定义
// 如果编译时找不到定义，需要包含相应的头文件
// #include <arkui/native_type.h>

// 默认的 Diff 回调实现 - 移到外部作为独立模板类
template<typename T>
class DefaultDiffCallback : public DiffUtil<T>::ItemCallback {
public:
    bool areItemsTheSame(const T& oldItem, const T& newItem) const override {
        return oldItem == newItem;
    }
    
    bool areContentsTheSame(const T& oldItem, const T& newItem) const override {
        return oldItem == newItem;
    }
    
    void* getChangePayload(const T& oldItem, const T& newItem) const override {
        return nullptr;
    }
};

// 增强的分页视图控制器 - 带异步差异计算功能，匹配 iOS PagingCollectionViewController
template<typename T>
class EnhancedPagingViewController {
private:
    // 基础控制器（使用组合模式）
    std::unique_ptr<PagingListViewController<T>> baseController_;
    
    // 用于后台差异计算的异步差异器
    std::unique_ptr<AsyncPagingDataDiffer<T>> differ_;
    
    // ListUpdateCallback 实现，用于 UI 更新
    class UpdateCallbackImpl : public ListUpdateCallback {
    private:
        PagingListViewController<T>* controller_;
        std::function<void()> updateUI_;
        std::function<void(int, int)> onInserted_;
        std::function<void(int, int)> onRemoved_;
        std::function<void(int, int)> onMoved_;
        std::function<void(int, int, void*)> onChanged_;
        
    public:
        UpdateCallbackImpl(PagingListViewController<T>* controller)
            : controller_(controller) {}
        
        void setCallbacks(
            std::function<void(int, int)> onInserted,
            std::function<void(int, int)> onRemoved,
            std::function<void(int, int)> onMoved,
            std::function<void(int, int, void*)> onChanged) {
            onInserted_ = onInserted;
            onRemoved_ = onRemoved;
            onMoved_ = onMoved;
            onChanged_ = onChanged;
        }
        
        void onInserted(int position, int count) override {
            if (onInserted_) onInserted_(position, count);
            // 实际实现中，这里会调用原生列表插入 API
        }
        
        void onRemoved(int position, int count) override {
            if (onRemoved_) onRemoved_(position, count);
            // 实际实现中，这里会调用原生列表删除 API
        }
        
        void onMoved(int fromPosition, int toPosition) override {
            if (onMoved_) onMoved_(fromPosition, toPosition);
            // 实际实现中，这里会调用原生列表移动 API
        }
        
        void onChanged(int position, int count, void* payload) override {
            if (onChanged_) onChanged_(position, count, payload);
            // 实际实现中，这里会调用原生列表更新 API
        }
    };
    
    std::unique_ptr<UpdateCallbackImpl> updateCallback_;
    
    // 自定义差异回调
    std::unique_ptr<typename DiffUtil<T>::ItemCallback> customDiffCallback_;
    
    // 原生视图句柄
    ArkUI_NodeHandle listNode_ = nullptr;
    
public:
    EnhancedPagingViewController() {
        initialize();
    }
    
    ~EnhancedPagingViewController() = default;
    
    // 初始化组件
    void initialize() {
        // 创建基础控制器
        baseController_ = std::make_unique<PagingListViewController<T>>();
        
        // 创建更新回调
        updateCallback_ = std::make_unique<UpdateCallbackImpl>(baseController_.get());
        
        // 创建默认差异回调
        auto diffCallback = std::make_unique<DefaultDiffCallback<T>>();
        
        // 创建异步差异器
        differ_ = std::make_unique<AsyncPagingDataDiffer<T>>(
            std::move(diffCallback),
            updateCallback_.get()
        );
        
        // 获取原生列表节点
        listNode_ = baseController_->getListNode();
    }
    
    // 提交分页数据（异步）- 匹配 iOS submitData
    std::future<void> submitData(const PagingData<T>& pagingData) {
        // 提交到差异器进行后台处理
        auto future = differ_->submitData(pagingData);
        
        // 同时更新基础控制器以立即更新 UI
        baseController_->submitData(pagingData);
        
        return future;
    }
    
    // 刷新数据 - 匹配 iOS refresh()
    void refresh() {
        differ_->refresh();
        baseController_->refresh();
    }
    
    // 重试失败的加载 - 匹配 iOS retry()
    void retry() {
        differ_->retry();
        baseController_->retry();
    }
    
    // 获取指定位置的项目 - 匹配 iOS getItem()
    std::shared_ptr<PagingItem<T>> getItem(int position) const {
        return differ_->getItem(position);
    }
    
    // 查看项目但不触发占位符 - 匹配 iOS peek()
    std::shared_ptr<PagingItem<T>> peek(int index) const {
        return differ_->peek(index);
    }
    
    // 获取当前快照 - 匹配 iOS snapshot()
    ItemSnapshotList<T> snapshot() const {
        return differ_->snapshot();
    }
    
    // 获取项目数量 - 匹配 iOS itemCount
    size_t itemCount() const {
        return differ_->itemCount();
    }
    
    // 获取原生节点句柄
    ArkUI_NodeHandle getListNode() const {
        return listNode_;
    }
    
    // 设置自定义项目构建器
    void setItemBuilder(std::function<ArkUI_NodeHandle(std::shared_ptr<PagingItem<T>>, int)> builder) {
        baseController_->setItemBuilder(builder);
    }
    
    // 设置自定义差异回调
    void setDiffCallback(std::unique_ptr<typename DiffUtil<T>::ItemCallback> callback) {
        customDiffCallback_ = std::move(callback);
        
        // 使用新回调重新创建差异器
        differ_ = std::make_unique<AsyncPagingDataDiffer<T>>(
            std::move(customDiffCallback_),
            updateCallback_.get()
        );
    }
    
    // 设置更新回调
    void setUpdateCallbacks(
        std::function<void(int, int)> onInserted,
        std::function<void(int, int)> onRemoved,
        std::function<void(int, int)> onMoved,
        std::function<void(int, int, void*)> onChanged) {
        updateCallback_->setCallbacks(onInserted, onRemoved, onMoved, onChanged);
    }
    
    // 加载状态流 - 匹配 iOS loadStateFlow
    CombinedLoadStates loadStateFlow() const {
        return differ_->loadStateFlow();
    }
    
    // 添加加载状态监听器 - 匹配 iOS addLoadStateListener
    void addLoadStateListener(std::function<void(const CombinedLoadStates&)> listener) {
        differ_->addLoadStateListener(listener);
    }
    
    // 移除加载状态监听器 - 匹配 iOS removeLoadStateListener
    void removeLoadStateListener(const std::function<void(const CombinedLoadStates&)>& listener) {
        differ_->removeLoadStateListener(listener);
    }
    
    // 添加页面更新监听器 - 匹配 iOS addOnPagesUpdatedListener
    void addOnPagesUpdatedListener(std::function<void()> listener) {
        differ_->addOnPagesUpdatedListener(listener);
    }
    
    // 移除页面更新监听器 - 匹配 iOS removeOnPagesUpdatedListener
    void removeOnPagesUpdatedListener(const std::function<void()>& listener) {
        differ_->removeOnPagesUpdatedListener(listener);
    }
    
    // 滚动控制
    void scrollToPosition(int position) {
        baseController_->scrollToPosition(position);
    }
    
    void scrollToTop() {
        baseController_->scrollToTop();
    }
    
    void scrollToBottom() {
        baseController_->scrollToBottom();
    }
};

// 网格版本的增强控制器
template<typename T>
class EnhancedPagingGridViewController {
private:
    // 基础网格控制器
    std::unique_ptr<PagingGridViewController<T>> baseController_;
    
    // 异步差异器
    std::unique_ptr<AsyncPagingDataDiffer<T>> differ_;
    
    // 网格的更新回调
    class GridUpdateCallbackImpl : public ListUpdateCallback {
    private:
        PagingGridViewController<T>* controller_;
        
    public:
        GridUpdateCallbackImpl(PagingGridViewController<T>* controller)
            : controller_(controller) {}
        
        void onInserted(int position, int count) override {
            // 网格特定的插入处理
        }
        
        void onRemoved(int position, int count) override {
            // 网格特定的删除处理
        }
        
        void onMoved(int fromPosition, int toPosition) override {
            // 网格特定的移动处理
        }
        
        void onChanged(int position, int count, void* payload) override {
            // 网格特定的更改处理
        }
    };
    
    std::unique_ptr<GridUpdateCallbackImpl> updateCallback_;
    ArkUI_NodeHandle gridNode_ = nullptr;
    
public:
    EnhancedPagingGridViewController() {
        initialize();
    }
    
    void initialize() {
        baseController_ = std::make_unique<PagingGridViewController<T>>();
        updateCallback_ = std::make_unique<GridUpdateCallbackImpl>(baseController_.get());
        
        // 使用独立的 DefaultDiffCallback 类
        auto diffCallback = std::make_unique<DefaultDiffCallback<T>>();
        
        differ_ = std::make_unique<AsyncPagingDataDiffer<T>>(
            std::move(diffCallback),
            updateCallback_.get()
        );
        
        gridNode_ = baseController_->getGridNode();
    }
    
    // 网格配置
    void setColumnsTemplate(const std::string& template_) {
        baseController_->setColumnsTemplate(template_);
    }
    
    void setGaps(float columnGap, float rowGap) {
        baseController_->setGaps(columnGap, rowGap);
    }
    
    // 其他所有方法与列表版本类似
    std::future<void> submitData(const PagingData<T>& pagingData) {
        auto future = differ_->submitData(pagingData);
        baseController_->submitData(pagingData);
        return future;
    }
    
    void refresh() {
        differ_->refresh();
        baseController_->refresh();
    }
    
    void retry() {
        differ_->retry();
        baseController_->retry();
    }
    
    std::shared_ptr<PagingItem<T>> getItem(int position) const {
        return differ_->getItem(position);
    }
    
    std::shared_ptr<PagingItem<T>> peek(int index) const {
        return differ_->peek(index);
    }
    
    ItemSnapshotList<T> snapshot() const {
        return differ_->snapshot();
    }
    
    size_t itemCount() const {
        return differ_->itemCount();
    }
    
    ArkUI_NodeHandle getGridNode() const {
        return gridNode_;
    }
    
    void setItemBuilder(std::function<ArkUI_NodeHandle(std::shared_ptr<PagingItem<T>>, int)> builder) {
        baseController_->setItemBuilder(builder);
    }
    
    CombinedLoadStates loadStateFlow() const {
        return differ_->loadStateFlow();
    }
    
    void addLoadStateListener(std::function<void(const CombinedLoadStates&)> listener) {
        differ_->addLoadStateListener(listener);
    }
    
    void removeLoadStateListener(const std::function<void(const CombinedLoadStates&)>& listener) {
        differ_->removeLoadStateListener(listener);
    }
    
    void addOnPagesUpdatedListener(std::function<void()> listener) {
        differ_->addOnPagesUpdatedListener(listener);
    }
    
    void removeOnPagesUpdatedListener(const std::function<void()>& listener) {
        differ_->removeOnPagesUpdatedListener(listener);
    }
};

#endif // ENHANCED_PAGING_CONTROLLER_H